package com.ljs.springbootinit.mq;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.DeliverCallback;

import java.util.HashMap;
import java.util.Map;

public class DlxDirectConsumer {
    private static final String Dead_EXCHANGE_NAME = "dlx_direct-exchange";
    private static final String WORK_EXCHANGE_NAME = "direct2-exchange";

    public static void main(String[] argv) throws Exception {
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost("localhost");
        Connection connection = factory.newConnection();
        Channel channel = connection.createChannel();
        channel.exchangeDeclare(WORK_EXCHANGE_NAME, "direct");
        channel.exchangeDeclare("some.exchange.name", "direct");
        //添加死信属性
        Map<String, Object> args = new HashMap<>();
        args.put("x-dead-letter-exchange",Dead_EXCHANGE_NAME );
        args.put("x-dead-letter-routing-key", "waibao");
        //创建队列
        String queueName1 = "xiaodog_queue";
        channel.queueDeclare(queueName1, true, false, false, args);
        channel.queueBind(queueName1, WORK_EXCHANGE_NAME, "xiaodog");

        //添加死信属性
        Map<String, Object> args2 = new HashMap<>();
        //要绑定到哪个交换机
        args2.put("x-dead-letter-exchange",Dead_EXCHANGE_NAME );
        //指定要发到那个死信队列
        args2.put("x-dead-letter-routing-key", "laoban");
        //创建队列
        String queueName2 = "xiaocat_queue";
        channel.queueDeclare(queueName2, true, false, false, args2);
        channel.queueBind(queueName2, WORK_EXCHANGE_NAME, "xiaocat");

        System.out.println(" [*] Waiting for messages. To exit press CTRL+C");

        DeliverCallback xiaowangdeliverCallback = (consumerTag, delivery) -> {
            String message = new String(delivery.getBody(), "UTF-8");
            channel.basicNack(delivery.getEnvelope().getDeliveryTag(),false,false);
            System.out.println(" [xiaodog] Received '" +
                    delivery.getEnvelope().getRoutingKey() + "':'" + message + "'");
        };
        DeliverCallback xiaolideliverCallback = (consumerTag, delivery) -> {
            String message = new String(delivery.getBody(), "UTF-8");
            channel.basicNack(delivery.getEnvelope().getDeliveryTag(),false,false);
            System.out.println(" [xiaocat] Received '" +
                    delivery.getEnvelope().getRoutingKey() + "':'" + message + "'");
        };
        channel.basicConsume(queueName1, false, xiaowangdeliverCallback, consumerTag -> {
        });
        channel.basicConsume(queueName2, false, xiaolideliverCallback, consumerTag -> {
        });
    }
}